package io.qar.mq.producer;

import io.qar.mq.entity.User;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

/**
 * @program: qar-cloud
 * @description:
 * @author: yyyyjinying
 * @create: 2023-10-13 16:36
 **/
@Service
public class DemoProducerService {
    @Resource
    private RocketMQTemplate rocketMQTemplate;


    public void producersMessage() {
        User user = new User();
        user.setAge(12);
        user.setName("zzz");
        rocketMQTemplate.convertAndSend("demoTopic", user);
    }

    public void sendOneWay(){
        User user = new User();
        user.setAge(12);
        user.setName("zzz");
        rocketMQTemplate.sendOneWay("demoTopic", user);

    }

    public void syncSend(){
        User user = new User();
        user.setAge(12);
        user.setName("zzz");
        Message<User> msg = MessageBuilder.withPayload(user).build();
        System.out.println("3秒后");
        rocketMQTemplate.syncSend("demoTopic", msg, 3000, 2);

    }

    public void asyncSend(){
        User user = new User();
        user.setAge(12);
        user.setName("zzz");
        Message<User> msg = MessageBuilder.withPayload(user).build();

        rocketMQTemplate.asyncSend("demoTopic", msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println(sendResult.getMsgId());
                System.out.println(sendResult.getSendStatus());
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println(throwable.getMessage());
                System.out.println(throwable.getCause());
            }
        }, 2000, 2);
    }

    public void syncSendOrderly(){
        User user = new User();
        user.setAge(12);
        user.setName("1001");
        Message<User> msg = MessageBuilder.withPayload(user).build();
        rocketMQTemplate.syncSendOrderly("demoTopic", msg, "1001");
        rocketMQTemplate.syncSendOrderly("demoTopic", msg, "1001");
        rocketMQTemplate.syncSendOrderly("demoTopic", msg, "1001");
        user.setName("1002");
        rocketMQTemplate.syncSendOrderly("demoTopic", msg, "1002");
        rocketMQTemplate.syncSendOrderly("demoTopic", msg, "1002");
        rocketMQTemplate.syncSendOrderly("demoTopic", msg, "1002");
    }





}
